<?php

namespace App\Exports;

use App\Models\AdminUser;
use App\Models\Config;
use App\Models\DdbFirstStatistic;
use App\Models\DdbLwStatistic;
use Dcat\Admin\Grid\Exporters\ExcelExporter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Lang;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Style\Border;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;

class DdbExporter extends AbstractExporter implements ShouldAutoSize,WithEvents,WithHeadings,FromArray
{
    use Exportable;

    protected $fileName;
    protected $activity_signups;
    protected $data_count_all;
    public $team;
    public $relation_model;
    public $relation_service;
    public $group_columns;
    public $universal_fields;
    public $last_row_number = 0; // 最后一列的编号数字 0 =>A, 1 => B 。。。。
    public $last_col_number = 5; // 最后一行的编号数字1,2,3,4.。。。。
    public $merge_cells = [];
    public $modelClass;
    public $edit_fields;
    public $tongji_text;
    public $admin_user;
    public $is_super_manger;

    public function __construct($modelClass, AdminUser $adminUser = null, $modelStatisticClass = null)
    {
        $this->admin_user = $adminUser;
        $this->modelClass = $modelClass;
        $this->fileName = $modelClass::NAME . date("ymdhis") .".xlsx";
        $is_super_manger = $this->admin_user->isSuperManger();
        $this->is_super_manger = $is_super_manger;
        if ($is_super_manger) {
            $this->edit_fields = ['name','dwzw','sex','mz','jg','xl','csrq','rdsj','cjgzsj','zdps', 'zdys', 'bz'];
            $filter_dwmc = request()->get('dwmc');
            if(is_array($filter_dwmc) && count($filter_dwmc) > 0){
                if(count($filter_dwmc) == 1){
                    $this->fileName = $filter_dwmc[0].'_'.$this->fileName;
                    if($modelStatisticClass != ''){
                        $this->tongji_text = $modelStatisticClass::where('dwmc', $filter_dwmc[0])->value('content');
                    }
                }
                if($this->tongji_text == ''){
                    $this->tongji_text = ' 党支部参加数   ，占   %；参加推荐的党员数     ，其中占正式党员数     %。';
                }
                $this->edit_fields = ['name','dwzw','sex','mz','jg','xl','csrq','rdsj','cjgzsj','dps', 'dys', 'bz'];
            }else{
                $this->tongji_text = ' 党支部参加数   ，占   %；参加推荐的党员数     ，其中占正式党员数     %。';
            }

        } else {
            $this->edit_fields = ['name','dwzw','sex','mz','jg','xl','csrq','rdsj','cjgzsj','dps', 'dys', 'bz'];
            if($modelStatisticClass != ''){
                $this->tongji_text = $modelStatisticClass::where('dwdm', $adminUser->ddb_dwdm)->value('content');
            }
            if($this->tongji_text == ''){
                $this->tongji_text = ' 党支部参加数   ，占   %；参加推荐的党员数     ，其中占正式党员数     %。';
            }
        }
        if (!env('SHOW_DDB_ZDY', 0) && $modelClass == 'App\Models\DdbFirst') {
            $this->edit_fields = collect($this->edit_fields)->filter(function($v) {
                return !in_array($v, ['zdps', 'zdys','dps', 'dys']);
            })->all();
        }
    }

    public function headings(): array
    {
        if($this->modelClass == 'App\Models\DdbLw'){
            $headers = [['选举单位推荐中共中国科学技术大学第十三届两委委员']];
        }else{
            $headers = [['中共中国科学技术大学第十三次代表大会代表候选人']];
        }

        $headers[] = [$this->modelClass::NAME];
        if($this->modelClass == 'App\Models\DdbFirst'){
            $headers[] = ['选举单位（盖章）：','','','','','','', '填报日期：    年   月    日'];
        }else{
            $headers[] = ['选举单位（盖章）：','','','','','','','','', '填报日期：    年   月    日'];
        }
        $headers[] = [$this->tongji_text];
        if($this->is_super_manger){
            $dwmc = request()->get('dwmc');
            if($this->modelClass != 'App\Models\DdbLw' || ($this->modelClass == 'App\Models\DdbLw' && is_array($dwmc) && count($dwmc) > 0)){
                $_subheaders = ['序号', '选举单位'];
            }else{
                $_subheaders = ['序号'];
            }
        }else{
            $_subheaders = ['序号'];
        }

        $trans = Lang::get('ddb-first.fields');
        $edit_fields = $this->edit_fields;
        foreach($edit_fields as $field) {
            $_title = isset($trans[$field]) ? $trans[$field] : $field;
            array_push($_subheaders, $_title);
        }
        $headers[] = $_subheaders;
        $this->last_row_number = count($_subheaders);
        array_push($this->merge_cells, 'A1:' . int3ExcelLetter($this->last_row_number-1) . '1');
        array_push($this->merge_cells, 'A2:' . int3ExcelLetter($this->last_row_number-1) . '2');
        array_push($this->merge_cells, 'A3:' . int3ExcelLetter($this->last_row_number-6) . '3');
        array_push($this->merge_cells, int3ExcelLetter($this->last_row_number-5).'3:' . int3ExcelLetter($this->last_row_number-1) . '3');
        array_push($this->merge_cells, 'A4:' . int3ExcelLetter($this->last_row_number-1) . '4');
        return $headers;
    }

    public function export()
    {
        // TODO: Implement export() method.
        $this->download($this->fileName)->prepare(request())->send();
        exit;
    }

    public function array(): array
    {
        $is_super_manger = $this->admin_user->isSuperManger();
        $build_data = [];
        $base_query = $this->modelClass::query()->orderBy('dwdm', 'asc')->orderBy('id', 'asc');
        if ($is_super_manger) { # 如果是组织部人员
            $dwmc = request()->get('dwmc');
            if(is_array($dwmc) && count($dwmc) > 0){
                $base_query->whereIn('dwmc', $dwmc);
            }else{
                $base_query->where('is_main', 1);
            }
        } else {
            $dwmc = null;
            $base_query->where('dwdm', $this->admin_user->ddb_dwdm);
        }
        $datas = $base_query->get();
        foreach($datas as $key => $data) {
            if($this->is_super_manger){
                if($this->modelClass != 'App\Models\DdbLw' || ($this->modelClass == 'App\Models\DdbLw' && is_array($dwmc) && count($dwmc) > 0)){
                    $row = [($key + 1), $data->dwmc];
                }else {
                    $row = [($key + 1)];
                }
            }else{
                $row = [($key + 1)];
            }
            foreach($this->edit_fields as $field) {
                $row[] = $data->$field;
            }
            array_push($build_data, $row);
            $this->last_col_number++;
        }
        return $build_data;
    }


    public function registerEvents(): array
    {
        return [
            AfterSheet::class  => function(AfterSheet $event) {
                // dd($this->merge_cells);
                $borders = [
                    'allBorders' => [
                        'borderStyle' => Border::BORDER_THIN,
                        'color' => [
                            'rgb' => '000000'
                        ]
                    ],
                ];
                $font = [
                    'name' => '宋体',
                    'bold' => false,
                    'size' => 11,
                    'italic' => false,
                    'strikethrough' => false,
                    'color' => [
                        'rgb' => '000000'
                    ]
                ];


                for($i=0; $i<$this->last_row_number;$i++) {
                    $event->sheet->getDelegate()->getColumnDimension(int3ExcelLetter($i))->setAutoSize(false)->setWidth(16);
                }

                for($i=1; $i<=$this->last_col_number;$i++) {
                    $event->sheet->getDelegate()->getRowDimension($i)->setRowHeight(28);
                }

                foreach($this->merge_cells as $merge_cell) {
                    $event->sheet->getDelegate()->mergeCells($merge_cell);//合并单元格
                }



                $event->sheet->getDelegate()->getStyle("A1:".(int3ExcelLetter($this->last_row_number-1).($this->last_col_number)))->getAlignment()->setVertical('center')->setHorizontal('left')->setWrapText(TRUE);
                $event->sheet->getDelegate()->getStyle('A5:'.(int3ExcelLetter($this->last_row_number-1).($this->last_col_number)))->applyFromArray([
                    'font' => $font,
                    'borders' => $borders
                ]);

                //第一行居中
                $first_font = $font;
                $first_font['size'] = '16';
                $first_font['name'] = '黑体';
                $first_font['bold'] = true;
                $event->sheet->getDelegate()->getStyle("A1:".(int3ExcelLetter($this->last_row_number-1).'1'))->getAlignment()->setVertical('center')->setHorizontal('center')->setWrapText(TRUE);
                $event->sheet->getDelegate()->getStyle("A2:".(int3ExcelLetter($this->last_row_number-1).'2'))->getAlignment()->setVertical('center')->setHorizontal('center')->setWrapText(TRUE);
                $event->sheet->getDelegate()->getStyle("A1:".(int3ExcelLetter($this->last_row_number-1).'1'))
                ->applyFromArray([
                    'font' => $first_font
                ]);
                $event->sheet->getDelegate()->getStyle("A2:".(int3ExcelLetter($this->last_row_number-1).'2'))
                ->applyFromArray([
                    'font' => $first_font
                ]);;



            }
        ];
    }
}